<template>
    <div :style="`transform: scale(${scale});`">
        <div class='page-container' >
            <div class="grid" v-for="(itemRow, i) in gridItemMap" :key="i">
                <div class="grid-item" v-for="(itemCol, j) in itemRow" :key="j">
                    <div class="black" v-show="itemCol === 1"></div>
                    <div class="white" v-show="itemCol === 2"></div>
                    <div class="tranparent" @click="chessDrop(i,j,playerRole)"></div>
                </div>
            </div>
        </div>
        <div class="button-wrapper">
            <button @click="gameStart()"  :disabled="permission" style="cursor:pointer;border:none;border-radius:5px;width:120px;height:35px;background: #67c23a;color:white;">开始(start)</button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <button  @click="gridInit()"  style="cursor:pointer;border:none;border-radius:5px;width:120px;height:35px;background: #909399;color:white">清空(clear)</button>
        </div> 
    </div>
    <loadingComp :visible="loading">
        <template #text>
            <p style="color:white">AI 思考中...(AI calculating...)</p>
        </template>
    </loadingComp>
</template>
<script setup>
import { onMounted,ref } from 'vue';
import loadingComp from './components/loadingComp.vue';
const gridItemMap = ref([]);
const playerRole = ref(0);
const round = ref(1);
const count = ref(0);
const permission = ref(false);
const loading = ref(false);
const scale = ref(1);
onMounted(()=>{
   scale.value =  window.innerWidth / 1920 - 0.15;
    gridInit();
})
// 创建 Web Worker 实例
const worker = new Worker(new URL('./worker.js', import.meta.url));

//初始化棋盘
const gridInit = ()=>{//0、无棋子,1、黑棋子,2、白棋子
    gridItemMap.value = [];
    permission.value = false;
    for(let i = 0; i < 16; i++){
        gridItemMap.value.push( Array(16).fill(0));
    }
}
//落子放置
const chessDrop = async (row,col,type)=>{
    if(!permission.value) return;
    //先判断是否可以落子  根据先后手 1先手为奇数，2后手为偶数 看玩家类型
    let flag = (count.value + 1)%2 === 0  && type === 2 || (count.value + 1)%2 !== 0  && type === 1;
    if(flag){
        gridItemMap.value[row][col] = type;
        let result = await checkIsOver();
        if(result){
            alert(`${type === playerRole.value?'你赢了(You win)':'AI赢了(AI win)'}`);
            gridInit();
            return;
        }
        loading.value = false;
        count.value++;
        if((count.value + 1)%2 === 0 && count.value !== 0){
            round.value++;
        }
    }
    fight();
}


// 设置玩家角色
const setRolesInWorker = (playerRole) => {
    worker.postMessage({ action: 'setRoles', data: { playerRole } });
};

// 使用 Web Worker 找到最佳移动
const findBestMoveWithWorker = () => {
    worker.postMessage({ action: 'findBestMove', data: { board: JSON.parse(JSON.stringify(gridItemMap.value)) } });
    worker.onmessage = function(e) {
        if (e.data.type === 'bestMove') {
            const [row, col] = e.data.data;
            chessDrop(row, col, playerRole.value === 1 ? 2 : 1);
        }
    };
};

const checkIsOver = ()=>{
    return new Promise((resolve) =>{
        worker.postMessage({ action: 'isGameOver', data: { board: JSON.parse(JSON.stringify(gridItemMap.value)) } });
        worker.onmessage = function(e) {
            if (e.data.type === 'gameOver') {
                const result = e.data.data;
                resolve(result);
            }
        };
    })
    
}

// 游戏开始时设置角色
const gameStart = async () => {
    permission.value = true;
    // 随机分配棋子
    let color = Math.floor(Math.random() * 2) + 1;
    playerRole.value = color;
    setRolesInWorker(color);
    const userConfirmed = window.confirm(`您目前是${color === 1 ? '先手黑子 (You are currently playing as Black (first move))' : '后手白子( You are currently playing as White (second move))'}`);
    if (userConfirmed) {
        fight();
    } else {
        permission.value = true;
    }
};


//对弈
const fight = async()=>{//判断当前回合落子方,
    if((count.value + 1)%2 !== 0){//奇回合
        if(playerRole.value === 2){//人类为白子后手
            loading.value = true;
            findBestMoveWithWorker();
        }
    }else{//偶回合
        if(playerRole.value === 1){//人类为黑子先手
            loading.value = true;
            findBestMoveWithWorker();
        }
    }
}


</script>

<style scoped>
.page-container{
        width:800px;
        height:800px;
        border:1px solid #000;
        margin:30px auto;
        background-color: rgb(172, 120, 42);
        position:relative;
        .grid{
            position: relative;
            align-items: center;
            height:50px;
            display: flex;
            .grid-item{
                width: 48px;
                height:48px;
                border:1px solid #000;
                position: relative;
            }
        }
        
    }
    .button-wrapper{
        display: flex;
        justify-content: center;
    }
    .black{
        background: black;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 1;
        box-shadow: inset 0 0 10px #8b8b8b79;
    }
    .white{
        background: white;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 1;
        box-shadow: inset 0 0 10px #00000079;
    }
    .tranparent{
        width: 48px;
        height: 48px;
        border-radius: 50%;
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 2;
        background: transparent;
        cursor: pointer;
    }
</style>
